package cn.com.dhcc.ddi.datasource.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.dbhandler.SingleTransationCircleWithOutResult;
import cn.com.dhcc.app.core.service.BaseService;
import cn.com.dhcc.ddi.datasource.dao.DataSourceDao;
import cn.com.dhcc.ddi.datasource.dao.DataSourceSQLserverDao;
import cn.com.dhcc.ddi.datasource.vo.DataSourceVo;
import cn.com.dhcc.ddi.datasource.vo.TableColVo;
import cn.com.dhcc.ddi.datasource.vo.TableInfoVo;
/**
 * 
 * SQL Server 服务类
 * @Author: fxx
 * @date: 2017-5-16
 *
 */
@Service
public class DataSourceSQLserverService extends BaseService {
	@Autowired
	DataSourceSQLserverDao dao;
	@Autowired
    DataSourceDao dataSourceDao;
	
	/**
	 * sqlserver
	 * @param vo
	 * @return
	 * @throws ServiceException
	 * @throws NiceException
	 */
	public List<TableInfoVo> getUserTableForSqlserver(DataSourceVo vo) throws ServiceException, NiceException{
		try {
			//根据数据源初始化dao
			dao.initDao(vo);
			final List<TableInfoVo> list = new ArrayList<TableInfoVo>();
			final List<TableInfoVo> userTableList  = getUserTablesForSqlserver();
			dao.getDao().doInSingleTransationCircle("元数据抽取", new SingleTransationCircleWithOutResult() {
				@Override
				public void actionInCircle() throws RuntimeException {
					try {
						for (Iterator<TableInfoVo> iterator = userTableList.iterator(); iterator.hasNext();) {
							TableInfoVo userTable = iterator.next();
							List<TableColVo> cols = dao.getUserTabColumnsForSqlserver(userTable.getSchema(), userTable.getTableName());
							userTable.setTableColVos(cols);
							list.add(userTable);
						}
					} catch (DaoException e) {
						throw new RuntimeException("获取表元数据错误", e);
					}
				}
			});
			return list;
		} catch (DaoException e) {
			throw new ServiceException("获取表元数据错误", e);
		}
	}
	/**
	 * 抽取表结构，包括授权和自建的表和视图  sqlserver
	 * @param vo
	 * @return
	 * @throws ServiceException
	 */
	public List<TableInfoVo> getUserTablesForSqlserver() throws ServiceException{
		List<TableInfoVo> userTableList = new ArrayList<TableInfoVo>();
		try {
			//抽取授权的表和视图
			userTableList.addAll( dao.getUserTablesForSqlserver());
		} catch (DaoException e) {
			throw new ServiceException("获取表元数据错误", e);
		}
		return userTableList;
	}
	/**
	 * 抽取表结构，包括授权和自建的表和视图  Oracle
	 * @param vo
	 * @return
	 * @throws ServiceException
	 */
	public String getDBNameForSqlserver() throws ServiceException{
		String dbName = "";
		try {
			 dbName = dao.getDBNameForSqlserver();
		} catch (DaoException e) {
			throw new ServiceException("获取表元数据错误", e);
		}
		return dbName;
	}

}
